﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Sykj.Components;
using Sykj.Infrastructure;
using Sykj.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sykj.Web.Areas.Manager.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class PermissionsController : MController
    {
        IPermissions _permissions;
        ICacheService _cacheService;

        /// <summary>
        /// 权限
        /// </summary>
        /// <param name="permissions"></param>
        /// <param name="cacheService"></param>
        public PermissionsController(IPermissions permissions, ICacheService cacheService)
        {
            _permissions = permissions;
            _cacheService = cacheService;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page">起始页</param>
        /// <param name="limit">页大小</param>
        /// <param name="keyWords">标题</param>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public IActionResult List(int page, int limit,string keyWords,int type)
        {
            StringBuilder strWhere = new StringBuilder(" 1=1 ");
            if (!string.IsNullOrWhiteSpace(keyWords))
            {
                strWhere.Append(" AND (Title.Contains(@0) OR Url.Contains(@0)) ");
            }
            if (type!=0)
            {
                strWhere.Append(" AND Type=@1 ");
            }
            var list = _permissions.GetPagedList(page, limit, strWhere.ToString(), " PermissionId desc ", keyWords, type);
            int recordCount = _permissions.GetRecordCount(strWhere.ToString(), keyWords, type);
            return Json(ListResult(list, recordCount));
        }

        /// <summary>
        /// 添加视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            ViewBag.PermissionsTreeList = BiudTreeOne();
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="permissions"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(Entity.Permissions permissions)
        {
            if (!ModelState.IsValid)
            {
                return Json(Failed("数据填写不完整"));
            }
            if (!string.IsNullOrWhiteSpace(permissions.Url))
            {
                permissions.Url = permissions.Url.ToLower();
            }
            else
            {
                permissions.Url = "";
            }
            permissions.CreateDate = DateTime.Now;
            permissions.Url = permissions.Url ?? "";
            bool b = _permissions.Add(permissions);
            _cacheService.RemoveCache(CacheKey.USERPERMISSIONSLIST);
            Components.LogOperate.Add("添加权限菜单", "添加ID为【" + permissions.PermissionId + "】的权限菜单", HttpContext);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(int id)
        {
            ViewBag.PermissionsTreeList = BiudTreeOne();
            var model = _permissions.GetModel(c => c.PermissionId == id);
            if (model == null)
            {
                return Content("查询不到数据！");
            }
            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="permissions"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Edit(Entity.Permissions permissions)
        {
            var model = _permissions.GetModel(c => c.PermissionId == permissions.PermissionId);
            if (model == null)
            {
                return Json(Failed("查询不到数据"));
            }
            model.ParentId = permissions.ParentId;
            model.Title = permissions.Title;
            model.Description = permissions.Description;
            model.Url = permissions.Url;
            model.Icon = permissions.Icon;
            model.Sort = permissions.Sort;
            model.IsEnable = permissions.IsEnable;
            model.Type = permissions.Type;
            model.Url = permissions.Url ?? "";
            bool b = _permissions.Update(model);
            _cacheService.RemoveCache(CacheKey.USERPERMISSIONSLIST);
            Components.LogOperate.Add("编辑权限菜单", "编辑ID为【" + permissions.PermissionId + "】的权限菜单", HttpContext);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DeleteAll(List<int> ids)
        {
            var list = _permissions.GetList(c => ids.Contains(c.PermissionId));
            bool b = _permissions.Delete(list);
            Components.LogOperate.Add("批量删除权限菜单", "删除ID为【" + string.Join(",", ids) + "】的权限", HttpContext);
            return Json(AjaxResult(b));
        }

        #region 绑定select
        private List<SelectListItem> BiudTreeOne()
        {
            List<SelectListItem> itemList = new List<SelectListItem>();
            itemList.Add(new SelectListItem { Text = "根目录", Value = "0" });

            var listAll = _permissions.GetList().ToList();
            if (listAll.Count > 0)
            {
                var listOne = listAll.Where(c => c.ParentId == 0);
                SelectListItem selectItem;
                foreach (var item in listOne)
                {
                    string text = item.Title;
                    text = "╋" + text;
                    selectItem = new SelectListItem
                    {
                        Text = text,
                        Value = item.PermissionId.ToString()
                    };
                    string blank = "├";
                    itemList.Add(selectItem);

                    BiudTree(item.PermissionId, itemList, listAll, blank);
                }
            }
            return itemList;
        }

        /// <summary>
        /// 递归查询，绑定select
        /// </summary>
        /// <param name="pId"></param>
        /// <param name="itemList"></param>
        /// <param name="dataList"></param>
        /// <param name="blank"></param>
        private void BiudTree(int pId, List<SelectListItem> itemList, List<Entity.Permissions> dataList, string blank)
        {
            var list = dataList.Where(c => c.ParentId == pId);
            SelectListItem selectItem;
            foreach (var item in list)
            {
                string text = item.Title;
                text = blank + "『" + text + "』";

                selectItem = new SelectListItem
                {
                    Text = text,
                    Value = item.PermissionId.ToString()
                };

                itemList.Add(selectItem);
                string blank2 = blank + "─";
                BiudTree(item.PermissionId, itemList, dataList, blank2);
            }
        }

        #endregion
    }
}